'use strict';

const RouterService = require('../base');
const wxConfig = require("../../../config/wx");
const WXBizDataCrypt = require('../../../config/WXBizDataCrypt');
const axios = require('axios');
const { OrderStatusEnum, BalanceLogTypeEnum } = require('../../utils/enum');

class TravelShareOrderService extends RouterService {
  static get modelName() {
    return 'Business.TravelShareOrder';
  }
  getListInclude() {
    return [
      {
        model: this.ctx.model.Business.TravelOrder,
        as: 'travelOrder',
        include: [
          {
              model: this.ctx.model.Business.TravelOrderItem,
              as: 'travelOrderItems',
          }
        ]
      },
      {
        model: this.ctx.model.Business.User,
        as: 'user'
      },
      {
        model: this.ctx.model.Business.User,
        as: 'distributor'
      },
      {
        model: this.ctx.model.Business.Travel,
        as: 'travel'
      },
      {
        model: this.ctx.model.Business.TravelSku,
        as: 'travelSku'
      },
      {
        model: this.ctx.model.Business.TravelSkuStock,
        as: 'travelSkuStock'
      },
    ]
  }
  getDetailInclude() {
    return this.getListInclude()
  }
  getPageInclude() {
    return this.getListInclude()
  }
  async create(payload) {
    // 判断余额是否足够
    const user = await this.ctx.model.Business.User.findOne({
      where: {
        id: payload.distributor_id
      }
    })
    if (!user) {
      throw new Error('用户不存在');
    }
    // 创建事务
    const transaction = await this.ctx.model.transaction();
    try {
        // 创建订单,
        const result = await this.model.create({
          ...payload,
          create_time: new Date()
        }, { transaction });

        if (payload.prepay_amount) {
          // 判断余额是否足够
          if (user.balance < payload.prepay_amount) {
            throw new Error('余额不足');
          }
          // 扣减预付金额
          await this.ctx.model.Business.User.update({
            balance: this.ctx.model.Sequelize.literal(`balance - ${payload.prepay_amount}`)
          }, {
            where: {
              id: payload.distributor_id
            },
            transaction
          })

          // 创建消费记录
          await this.ctx.model.Business.BalanceRecord.create({
            travel_share_order_id: result.id,
            user_id: payload.distributor_id,
            amount: -payload.prepay_amount,
            type: BalanceLogTypeEnum.DISTRIBUTOR_CONSUME,
            description: `创建代付订单`,
          }, { transaction });
        }
        const qrcode = await this.ctx.service.common.qrcode.getQrcode('pages/travelOrder/shareOrder?id=' + result.id)

        await this.model.update({
          qrcode: qrcode
        }, {
          where: {
            id: result.id
          },
          transaction
        })
        await transaction.commit();
        return await this.findById(result.id)
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }
  async cancel(id) {
    const order = await this.model.findOne({
      where: {
        id
      },
      include: [
        {
          model: this.ctx.model.Business.TravelOrder,
          as: 'travelOrder',
        }
      ]
    })
    if (!order) {
      throw new Error('订单不存在');
    }
    if (order.travelOrder && order.travelOrder.status !== OrderStatusEnum.PENDING) {
      throw new Error('客户已下单，无法取消');
    }
    // 创建事务
    const transaction = await this.ctx.model.transaction();
    try {
      if (order.travelOrder && order.travelOrder.status === OrderStatusEnum.PENDING) {
        // 先取消客户订单
        await this.ctx.model.Business.TravelOrder.update({
          status: OrderStatusEnum.CANCELLED,
          cancel_time: new Date()
        }, {
          where: {
            id: order.travelOrder.id
          },
          transaction
        })
      }
      await this.cancelOrder(order, transaction)
      await transaction.commit();
      return true
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }

  async cancelOrder(order, transaction) {
      // 退款
      await this.ctx.model.Business.TravelShareOrder.update({
        status: OrderStatusEnum.CANCELLED
      }, {
        where: {
          id: order.id
        },
        transaction
      })
      // 增加余额
      await this.ctx.model.Business.User.update({
        balance: this.ctx.model.Sequelize.literal(`balance + ${order.prepay_amount}`)
      }, {
        where: {
          id: order.distributor_id
        },
        transaction
      })
      // 增加分销退款记录
      await this.ctx.model.Business.BalanceRecord.create({
        travel_share_order_id: order.id,
        user_id: order.distributor_id,
        amount: order.prepay_amount,
        type: BalanceLogTypeEnum.DISTRIBUTOR_CONSUME_REFUND,
        description: `代付订单退款`,
      }, { transaction });
      return true
  }
}

module.exports = TravelShareOrderService;
